<template>
    <div class="wh-100 fs-14 overflow-auto" style="background-color:#fff;">
        <!--title&导出台账&返回-->
        <div class="d-flex-between-center px-12 head-box" >
            <div class="fs-16 fw-7">添加帮扶对象</div>
            <div>
                <Button @click=" back()">返回</Button>
                <Button type="primary" @click="handleExportData" :disabled="loading">+导出台账</Button>
            </div>
        </div>
        <div class="px-12 mt-12 mb-36">
            <table class="w-100">
                <tr class="w-100 tr01" >
                    <td colspan="7" class="w-100 fs-18 fw-7" style="color: black">{{ schoolName }}毕业生重点群体就业帮扶工作台账</td>
                </tr>
                <tr  class="tr02" >
                    <td colspan="3">院系：{{ basicData.college }}</td>
                    <td class="td-title"></td>
                    <td colspan="3">专业：{{ basicData.profession }}</td>
                </tr>
                <tr class="tr02">
                    <td rowspan="4" class="td-title">帮扶对象</td>
                    <td class="td-title">姓名</td>
                    <td class="td-content">{{ basicData.name }}</td>
                    <td>性别</td>
                    <td class="td-content">{{ basicData.sex }}</td>
                    <td class="td-title">民族</td>
                    <td class="td-content">{{ basicData.ethnic }}</td>
                </tr>
                <tr class="tr02">
                    <td>毕业时间</td>
                    <td>
                        {{ basicData.graduationTime }}
                    </td>
                    <td>学历层次</td>
                    <td>{{ basicData.educationalLevel }}</td>
                    <td>政治面貌</td>
                    <td>{{ basicData.politicalStatus }}</td>
                </tr>
                <tr class="tr02">
                    <td>出生日期</td>
                    <td>
                        {{ basicData.birthday }}
                    </td>
                    <td>身份证号</td>
                    <td colspan="3">{{ basicData.idCard }}</td>
                </tr>
                <tr class="tr02">
                    <td>联系方式</td>
                    <td>{{ basicData.mobile }}</td>
                    <td>家庭联系人</td>
                    <td>{{ basicData.familyContact }}</td>
                    <td>家庭电话</td>
                    <td>{{ basicData.homeMobile }}</td>
                </tr>
                <tr class="tr02">
                    <td>类别</td>
                    <td colspan="6">{{ basicData.helpCategory }}</td>
                </tr>
                <tr class="tr02">
                    <td>帮扶人</td>
                    <td>姓名</td>
                    <td>{{ basicData.helperName }}</td>
                    <td>职务</td>
                    <td>{{ basicData.helperJob }}</td>
                    <td>联系电话</td>
                    <td>{{ basicData.helperPhone }}</td>
                </tr>

                <tr class="tr02">
                    <td :rowspan="26">
                        帮扶措施
                    </td>
                    <td colspan="2">帮扶类别</td>
                    <td colspan="4">帮扶内容</td>
                </tr>
                <template v-for="(item, index) in heartList">
                    <tr class="tr02">
                        <td :rowspan="heartList.length * 2" v-if="index === 0">谈心谈话记录</td>
                        <td rowspan="2">第{{ index + 1 }}次</td>
                        <td>时间</td>
                        <td>{{ item.heartTalkTime }}</td>
                        <td>地点</td>
                        <td>{{ item.heartTalkPlace }}</td>
                    </tr>
                    <tr class="tr02">
                        <td>谈话内容</td>
                        <td colspan="3">{{ item.heartTalkContext }}</td>
                    </tr>
                </template>
                <template v-for="(item, index) in employList">
                    <tr class="tr02">
                        <td :rowspan="employList.length * 2" v-if="index === 0">参加就业促进活动情况</td>
                        <td rowspan="2">第{{ index + 1 }}次</td>
                        <td>活动名称</td>
                        <td colspan="3">{{ item.employPro }}</td>
                    </tr>
                    <tr class="tr02">
                        <td>参加时间</td>
                        <td colspan="3">{{ item.employProTime }}</td>
                    </tr>
                </template>
                <template v-for="(item, index) in recommendList">
                    <tr class="tr02">
                        <td :rowspan="recommendList.length * 4" v-if="index === 0">推荐岗位</td>
                        <td rowspan="4">第{{ index + 1 }}次</td>
                        <td>单位名称</td>
                        <td colspan="3">{{ item.recommendEnterpriseName }}</td>
                    </tr>
                    <tr class="tr02">
                        <td>岗位名称</td>
                        <td colspan="3">{{ item.recommendPositionName }}</td>
                    </tr>
                    <tr class="tr02">
                        <td>单位联系人</td>
                        <td>{{ item.recommendPeopleName }}</td>
                        <td>联系方式</td>
                        <td>{{ item.recommendMobile }}</td>
                    </tr>
                    <tr class="tr02">
                        <td>推荐时间</td>
                        <td>{{ item.recommendTime }}</td>
                        <td>是否签约</td>
                        <td>{{ item.recommendSign === 1 ? '是' : item.recommendSign === 0 ? '否' : '' }}</td>
                    </tr>
                </template>

                <tr class="tr03" >
                    <td>其他帮扶措施</td>
                    <td colspan="5">{{ other }}</td>
                </tr>
                <tr class="tr02">
                    <td rowspan="3">帮扶结果</td>
                    <td rowspan="2">已落实毕业去向</td>
                    <td>毕业去向</td>
                    <td colspan="2">{{ basicData.employmentStatus }}</td>
                    <td>落实时间</td>
                    <td>
                        {{ basicData.implementationTime }}
                    </td>
                </tr>
                <tr class="tr02">
                    <td>单位名称</td>
                    <td colspan="4">{{ basicData.enterpriseName }}</td>
                </tr>
                <tr class="tr03">
                    <td>未落实毕业去向</td>
                    <td>原因</td>
                    <td colspan="4">{{ basicData.unImplementationReason }}</td>
                </tr>
                <tr class="tr02">
                    <td>数据核对情况</td>
                    <td colspan="6">
                        {{ basicData.dataCheckCondition ==='其他' ? basicData.dataCheckOther : basicData.dataCheckCondition }}
                    </td>

                </tr>
                <tr class="tr02">
                    <td>帮扶人签名</td>
                    <td colspan="5"></td>
                    <td></td>
                </tr>
                <tr class="tr03">
                    <td>院系意见</td>
                    <td colspan="5"></td>
                    <td></td>
                </tr>
                <tr class="tr03">
                    <td>就业工作主管部门意见</td>
                    <td colspan="5"></td>
                    <td></td>
                </tr>
            </table>
        </div>
    </div>
</template>
<script>
import { getSelectMap, getHardshipSupportById, getProfessionNameByProfCode } from '@/api/hardshipSupport';
import { excelExport, getTitleByValue } from '@/views/hardshipSupport/util';
import moment from 'moment/moment';
import { addHelpersData, lookStandingBookData } from '@/views/hardshipSupport/data';
import PizZipUtils from 'pizzip/utils/index.js';
import PizZip from 'pizzip';
import Docxtemplater from 'docxtemplater';
export default {
    data() {
        return {
            // 应用数据
            ...lookStandingBookData,
            // UI 数据
            loading: true,
          pageIndex:1
        };
    },
    computed: {
        moment() {
            return moment;
        }
    },
    mounted() {
        // 从url中获取id
        this.initData(this.$route.query.id);
      this.pageIndex =  this.$route.query.pIndex || 1
    },
    methods: {
        async initData(id) {
            const closeMsg = this.$Message.loading({
                content: '正在加载数据',
                duration: 0
            });
            let { result, message } = await getHardshipSupportById({
                id: id
            });
            console.log('网络拿到的数据', result);
            await this.dataFormat(result);

            closeMsg();
            this.$Message.success({
              content: message,
              duration: 2,
              closable: true
            });
            this.loading = false;
        },
      back(){

        this.$router.replace({
          path: '/hardshipSupport',
          query:{
            pageIndex :this.pageIndex
          }
        });
      },
        // 将从网络拿到的数据格式化到表格
        async dataFormat(result) {
            //<editor-fold desc="处理基础数据">
            let basicData = result.basic;
            // 性别 民族 教育水平 政治面貌 所属院系 就业状态
            let map;
            try {
                map = await getSelectMap(false);
            } catch (e) {
                map = [];
            }
            // 根据专业id查找专业名字
            // let profession = '';
            // if (basicData.profession) {
            //     let professionList = await getProfessionNameByProfCode(basicData.profession);
            //     if (Array.isArray(professionList.result) && professionList.result.length > 0) {
            //         profession = professionList.result.find(item => {
            //             return item.gradLevelDict === basicData.educationalLevel;
            //         }).title;
            //     }
            // }

            // 性别 这里性别一定是数字
            if (basicData.sex !== undefined && Number.isInteger(basicData.sex)) {
                basicData.sex += '';
            }
            let sex = getTitleByValue(map[0].result, basicData.sex);
            let ethnic = getTitleByValue(map[1].result, basicData.ethnic);
            let educationalLevel = getTitleByValue(map[2].result, basicData.educationalLevel);
            let politicalStatus = getTitleByValue(map[3].result, basicData.politicalStatus);
            let employmentStatus = getTitleByValue(map[5].result, basicData.employmentStatus);

            basicData = { ...basicData, sex, ethnic, educationalLevel, politicalStatus, profession:result.basic.profession, employmentStatus };
            if (basicData.helpResult === 0) {
                basicData.employmentStatus = '';
                basicData.implementationTime = '';
                basicData.enterpriseName = '';
            } else {
                basicData.unImplementationReason = '';
            }
            // 处理帮扶类别
            let helpCategory = basicData.helpCategory ?? ' ';

            let helpCategoryString = '';
            if (Array.isArray(helpCategory)) {
                helpCategory.forEach(item => {
                    helpCategoryString += item + ',';
                });
            }
            basicData.helpCategory = helpCategoryString.substring(0, helpCategoryString.length - 1);

            // 处理三个日期
            basicData.graduationTime = moment(basicData.graduationTime).format('YYYY-MM-DD') === 'Invalid date' ? '' : moment(basicData.graduationTime).format('YYYY-MM-DD');
            basicData.birthday = moment(basicData.birthday).format('YYYY-MM-DD') === 'Invalid date' ? '' : moment(basicData.birthday).format('YYYY-MM-DD');
            basicData.implementationTime = moment(basicData.implementationTime).format('YYYY-MM-DD') === 'Invalid date' ? '' : moment(basicData.implementationTime).format('YYYY-MM-DD');
            //</editor-fold>
            //<editor-fold desc="处理就业活动">
            let employList = result.employList ?? [];
            // 如果长度大于3 只截取前三条
            if (employList.length > 3) employList = employList.slice(0, 3);

            // 如果长度小于3 补齐到3
            if (employList.length < 3) {
                let length = employList.length;
                for (let i = 0; i < 3 - length; i++) {
                    employList.push(this.employListBase);
                }
            }

            //</editor-fold>
            //<editor-fold desc="处理谈心谈话">
            let heartList = result.heartList ?? [];
            if (heartList.length > 3) heartList = heartList.slice(0, 3);
            // 如果长度小于3 补齐
            if (heartList.length < 3) {
                let length = heartList.length;
                for (let i = 0; i < 3 - length; i++) {
                    heartList.push(this.heartListBase);
                }
            }
            //</editor-fold>
            //<editor-fold desc="处理推荐">
            let recommendList = result.recommendList ?? [];
            if (recommendList.length > 3) recommendList = recommendList.slice(0, 3);
            // 如果长度小于3 补齐
            if (recommendList.length < 3) {
                let length = recommendList.length;
                for (let i = 0; i < 3 - length; i++) {
                    recommendList.push(this.recommendListBase);
                }
            }
            //</editor-fold>
            //<editor-fold desc="处理其他">
            let other = result.other ?? { other: '' };
            // 如果长度小于3 补齐

            //</editor-fold>

            // 应用数据
            Object.keys(this.basicData).forEach(key => {
                this.basicData[key] = basicData[key] ?? '';
            });
            this.employList = employList;
            this.heartList = heartList;
            this.recommendList = recommendList;
            this.other = other.other;

            // 保存学校名称
            this.schoolName = basicData.schoolName;
        },

        async handleExportData() {
            // 从data中拿到所有值
            let basicData = this.basicData;
            // 将heartList列表展开 每个item的属性带上_1 _2 _3的
            let heartList = {};
            this.heartList.forEach((item, index) => {
                Object.keys(item).forEach(key => {
                    heartList[key + '_' + (index + 1)] = item[key];
                });
            });
            // 将employList列表展开 每个item的属性带上_1 _2 _3的
            let employList = {};
            this.employList.forEach((item, index) => {
                Object.keys(item).forEach(key => {
                    employList[key + '_' + (index + 1)] = item[key];
                });
            });

            // 将recommendList的item中的recommendSign 改为 是或者 否
            let recommendListHandledSign = this.recommendList.map(item => {
                return {
                    ...item,
                    recommendSign: item.recommendSign === 1 ? '是' : item.recommendSign === 0 ? '否' : ''
                };
            });

            // 将recommendList列表展开 每个item的属性带上_1 _2 _3的
            let recommendList = {};
            recommendListHandledSign.forEach((item, index) => {
                Object.keys(item).forEach(key => {
                    recommendList[key + '_' + (index + 1)] = item[key];
                });
            });

            // 数据核对情况
            basicData.dataCheckCondition = basicData.dataCheckCondition === '其他' ? basicData.dataCheckOther : basicData.dataCheckCondition;

            // other 没处理
            let data = {
                ...basicData,
                ...heartList,
                ...employList,
                ...recommendList,
                other: this.other,
                schoolName: this.schoolName
            };
            console.log(data);
            await this.handleExport(data);
        },

        handleExport(data) {
            const url = window.location.origin + '/困难帮扶台账生成模板.docx';
            return new Promise((resolve, reject) => {
                PizZipUtils.getBinaryContent(url, function(error, content) {
                    if (error) {
                        reject(error);
                    }
                    const zip = new PizZip(content);
                    const doc = new Docxtemplater(zip);
                    doc.render({
                        ...data
                    });
                    const blob = doc.getZip().generate({
                        type: 'blob',
                        mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                        compression: 'DEFLATE'
                    });
                    // 下载blob
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = '困难帮扶台账.docx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                    resolve();
                });
            });
        }
    },
    beforeDestroy() {
        // 全局销毁Message
        this.$Message.destroy();
    }
};
</script>
<style lang="less" scoped>
td {
    border: 1px solid #000000;
    text-align: center;
    vertical-align: middle;
}

.td-title {
    width: 200px;
}

.td-content {
    width: 240px;
}

.head-box {
    height: 60px;
    border-bottom: 1px solid #eef1f7
}
.tr01 {
   height: 50px;
   line-height: 50px
}
.tr02 {
    height: 40px
}
.tr03 {
    height: 80px
}
</style>
